package com.itcam.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcam.article.mapper.ApArticleConfigMapper;
import com.itcam.article.mapper.ApArticleContentMapper;
import com.itcam.article.mapper.ApArticleMapper;
import com.itcam.article.service.ApArticleService;
import com.itcam.article.service.ArticleFreemarkerService;
import com.itcam.common.constants.ArticleConstants;
import com.itcam.common.constants.BehaviorConstants;
import com.itcam.common.redis.CacheService;
import com.itcam.model.article.dtos.ArticleDto;
import com.itcam.model.article.dtos.ArticleHomeDto;
import com.itcam.model.article.dtos.ArticleInfoDto;
import com.itcam.model.article.pojos.ApArticle;
import com.itcam.model.article.pojos.ApArticleConfig;
import com.itcam.model.article.pojos.ApArticleContent;
import com.itcam.model.article.vos.HotArticleVo;
import com.itcam.model.common.dtos.ResponseResult;
import com.itcam.model.common.enums.AppHttpCodeEnum;
import com.itcam.model.mess.ArticleVisitStreamMess;
import com.itcam.model.user.pojos.ApUser;
import com.itcam.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    private final CacheService cacheService;

    public ApArticleServiceImpl(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    /**
     * 根据参数加载文章列表
     * @param loadtype
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        // 1.校验参数
        // 从dto中获取用户请求的页面大小，如果未指定，则默认为10
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        // 限制页面大小的最大值为MAX_PAGE_SIZE
        size = Math.min(size, MAX_PAGE_SIZE);
        // 将处理后的页面大小重新设置到dto中
        dto.setSize(size);
        // 2.类型参数校验
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 3.文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 4.时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        // 5.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        // 6.返回结果
        return ResponseResult.okResult(apArticles);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    /**
     * 保存app端相关文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        // 1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = new ApArticle();

        BeanUtils.copyProperties(dto, apArticle);
        // 2.判断是否存在id
        if (dto.getId() == null) {
            // 不存在，保存文章 保存文章配置 保存文章内容
            // 保存文章
            this.save(apArticle);
            // 保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);
            // 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        } else {
            // 存在，修改文章  修改文章内容
            // 修改文章
            this.updateById(apArticle);
            // 修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }
        // 3.异步调用生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        // 4.返回文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 数据回显
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        // 1.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /*
            {
               "isfollow": true,
               "islike": true,
               "isunlike": false,
               "iscollection": true
            }
        */
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;
        // 2.判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null) {
            // 喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson)) {
                islike = true;
            }
            // 不喜欢的行为
            String unlikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(unlikeBehaviorJson)) {
                isunlike = true;
            }
            // 收藏的行为
            String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(collectionJson)) {
                iscollection = true;
            }
            // 关注的行为
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getArticleId().toString());
            if (score != null) {
                isfollow = true;
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 加载文章列表
     * @param dto
     * @param type  1 加载更多   2 加载最新
     * @param firstPage  true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        // 判断是否是第一页
        if (firstPage) {
            // 从缓存中获取数据
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            // 判断缓存中是否有数据
            if (StringUtils.isNotBlank(jsonStr)) {
                // 将缓存中的数据转换为列表
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                // 返回数据
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        // 如果不是第一页或者缓存中没有数据，则调用 load 方法加载数据
        return load(type, dto);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        // 1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = this.updateArticle(mess);
        // 2.计算文章的分值
        Integer score = this.computeScore(apArticle);
        score = score * 3;
        // 3.替换当前文章对于频道的热点数据
        this.replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        // 4.替换推荐对于的热点数据
        this.replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 更新文章行为数量
     * @param mess
     * @return
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        // 根据消息中的文章ID获取文章对象
        ApArticle apArticle = this.getById(mess.getArticleId());
        // 如果文章对象存在
        if (apArticle != null) {
            // 更新文章的浏览量
            apArticle.setViews(apArticle.getViews() + mess.getView());
            // 更新文章的点赞数
            apArticle.setLikes(apArticle.getLikes() + mess.getLike());
            // 更新文章的评论数
            apArticle.setComment(apArticle.getComment() + mess.getComment());
            // 更新文章的收藏数
            apArticle.setCollection(apArticle.getCollection() + mess.getCollect());
            // 更新文章对象
            this.updateById(apArticle);
        }
        // 返回更新后的文章对象
        return apArticle;
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        // 初始化文章热度得分为0
        Integer score = 0;
        // 如果文章的点赞数不为空，则将点赞数乘以点赞权重并加到热度得分中
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 如果文章的浏览量不为空，则将浏览量加到热度得分中
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        // 如果文章的评论数不为空，则将评论数乘以评论权重并加到热度得分中
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 如果文章的收藏数不为空，则将收藏数乘以收藏权重并加到热度得分中
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        // 返回文章的热度得分
        return score;
    }

    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListenStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListenStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListenStr, HotArticleVo.class);

            boolean flag = true;

            // 如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            // 如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() > 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo newHot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, newHot);
                        newHot.setScore(score);
                        hotArticleVoList.add(newHot);
                    }
                }
                // 如果缓存中数据没有存满，直接添加
                else {
                    HotArticleVo newHot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, newHot);
                    newHot.setScore(score);
                    hotArticleVoList.add(newHot);
                }
            }
            // 缓到redis
            hotArticleVoList = hotArticleVoList.stream()
                    .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                    .collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));
        }
    }


}